<?php
class Upload extends MY_Controller
{

	/**
	* 下载js上传的微信图片
	* @return [type] [description]
	*/
	function downloadWxImage(){
		$post = $this->input->post();
		$media_id = $post['media_id'];

		$this->load->model('Weixin_model','wx');
		$access_token = $this->wx->getAccessToken();//获取token
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
		$fileinfo = $this->httpGet($url);
		$path = dirname(APPPATH)."/img/";
		$filename = $this->getFileName();
		$filepath = $path.$filename;
		//创建一个新的图片文件
		$fopen = fopen($filepath, 'wb');
		//将文件流写入图片
		fputs($fopen, $fileinfo['body']);
		//关闭资源
		fclose($fopen);
		$file = array(
				'name' => $filename,
				'tmp_name' => $filepath,
			);
		$return = $this->upload_img($file);

		//删除新增的图片
		unlink($filepath);
		echo json_encode($return);
	}

	/**
	* curl get请求
	* @param  [type] $url [description]
	* @return [type]      [description]
	*/
	function httpGet($url) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_NOBODY, 0); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		$package = curl_exec($curl);
		$httpinfo = curl_getinfo($curl);
		curl_close($curl);

		$imageAll = array_merge(array('header'=>$httpinfo),array('body'=>$package)); 
		return $imageAll;
	}


	/**
     * 上传图片到阿里云
     * @return [type] [description]
     */
    function upload_img($filedata){
		$this->load->library('Uploader/Uploader');
		$upload = new Uploader();
		$result = $upload->upload_aliyun($filedata['name'],$filedata['tmp_name']);
		if($result['error']==0){
		//上传成功
		$return = array(
				'code'=>1,
				'url'=>$result['url'],
				'msg'=>'图片已经上传成功',
			);
		//将图片添加到素材库
		$data[0] = array(
				'url'=>$result['url'],
				'create_time'=>date('Y-m-d H:i:s'),
				'type_img' => $result['type_img'],
				'filename' => $result['filename'],
				'objectName' => $result['objectName'],
				'type' =>1,
			);
		}else{
			//上传失败
			$return = array(
				'code'=>0,
				'msg'=>'图片上传失败,请重试',
			);
		}
		return $return;
	}

	/**
     * 设置文件（图片）名
     * [setFileName description]
     */
    function getFileName(){
      $image_name = md5(uniqid(rand())).".jpg"; 
      return $image_name;
    }

	/**
     * 保存图片
     */
    function saveUploadImg(){
    	$post=$this->input->post();

    	$_SESSION['imgUrl']=isset($post['url'])?$post['url']:'';
    	echo json_encode(array('code'=>'1','msg'=>'success','url'=>$_SESSION['imgUrl'],));
    }

}